package it.yuzuojian.com;



import it.yuzuojian.com.annotation.ioc.ComponentScan;
import it.yuzuojian.com.pojo.BeanDefinition;
import it.yuzuojian.com.pojo.BeanFactory;
import it.yuzuojian.com.util.ApplicationContextUtil;
import it.yuzuojian.com.util.ClassUtil;


import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ApplicationContext {
    private Class clazz;
    private BeanFactory beanFactory = new BeanFactory();
    private ApplicationContextUtil applicationContextUtil = new ApplicationContextUtil();

    int i = 0;

    public ApplicationContext(Class clazz) {
        this.clazz = clazz;
        init(clazz);
    }

    public ApplicationContext() {
    }

   
    public void init(Class aClass) {
        List<Class<?>> allClass = null;
        if (clazz.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan declaredAnnotation = (ComponentScan) clazz.getDeclaredAnnotation(ComponentScan.class);
            allClass = ClassUtil.getClasses(declaredAnnotation.value());
        } else {
            Package aPackage = aClass.getPackage();
            allClass = ClassUtil.getClasses(aPackage.getName());
        }
        applicationContextUtil.initBeanDefinitions(allClass);
        applicationContextUtil.initAspect();
        applicationContextUtil.initBeanPostProcessors();
        applicationContextUtil.initMVCDataHandle();
        applicationContextUtil.initWebMvcConfigurer();
    }

    public Object getBean(String beanName) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        ConcurrentHashMap<String, BeanDefinition> beanDefinitions = BeanFactory.getBeanDefinitions();
        ConcurrentHashMap<String, Object> originalObjects = BeanFactory.getOriginalObjects();
        ConcurrentHashMap<String, Object> singletonObjects = BeanFactory.getSingletonObjects();
        BeanDefinition beanDefinition = beanDefinitions.get(beanName);
        return applicationContextUtil.getBean(beanDefinition, originalObjects, singletonObjects);
    }

}
